/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package win.start.core;

import java.net.Socket;

import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.impl.DefaultBHttpClientConnection;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;

/**
 * 基于Http-Core，有点低级。
 * （一）顺序地执行多个GET请求。
 */
public class ElementalHttpGet {

	public static void main(String[] args) throws Exception{
		HttpProcessor httpproc = HttpProcessorBuilder.create() //干嘛的？
				.add(new RequestContent())
				.add(new RequestTargetHost())
				.add(new RequestConnControl())
				.add(new RequestUserAgent("Test/1.1"))//
				.add(new RequestExpectContinue(true)).build();

		HttpRequestExecutor httpexecutor = new HttpRequestExecutor();// 请求执行器

		HttpCoreContext coreContext = HttpCoreContext.create();
		HttpHost host = new HttpHost("localhost", 8080);// 同一个目标主机
		coreContext.setTargetHost(host);

		DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
		ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE; //干嘛的？链接重用策略，默认？默认就是重用？

		try{
			// 多个目标
			String[] targets = {
					"/index",
					"/a",
					"/b"};

			for(int i = 0; i < targets.length; i++){
				if(!conn.isOpen()){ //conn没打开的话
					Socket socket = new Socket(host.getHostName(), host.getPort()); //发起socket请求，这个每次循环都重新创建，不能复用？
					conn.bind(socket);//conn使用socket收发数据；该方法执行后，conn.isOpen()返回true
				}

				BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]); // 基本请求？？ 且只需要指定访问资源
				System.out.println(">> Request ProtocolVersion: " + request.getRequestLine().getProtocolVersion()); // 输出请求行？
				System.out.println(">> Request Method: " + request.getRequestLine().getMethod()); // 输出请求行？
				System.out.println(">> Request URI: " + request.getRequestLine().getUri()); // 输出请求行的uri？

				// 执行器处理并执行？
				httpexecutor.preProcess(request, httpproc, coreContext); // 预处理
				HttpResponse response = httpexecutor.execute(request, conn, coreContext);// 响应
				httpexecutor.postProcess(response, httpproc, coreContext);

				System.out.println("<< Response StatusLine: " + response.getStatusLine());
				System.out.println("<< Response Entity: " + response.getEntity());//[Content-Type: text/plain;charset=UTF-8,Content-Length: 5,Chunked: false]
				System.out.println("<< Response Entity - content: " + EntityUtils.toString(response.getEntity()));// 实际的内容？ response.content
				if(!connStrategy.keepAlive(response, coreContext)){ //判断链接策略是否(!alive)  这里，默认策略就是alive
					conn.close();
				} else{
					System.out.println("Connection kept alive..."); // 想知道alive的话，还能重用吗？
				}
				System.out.println("=======<br/>=======");
			}
		} finally{
			conn.close();
		}
	}

}
